iOS开发 GCD

1. GCD信号量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// 等待信号量
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// 发起网络请求
[BadgeCountModel HomeBadgeCountBlock:^(NSDictionary *data) {
NSNumber *num = data[@"num"];
if (num.integerValue > 0 ) {
weakSelf.rightBt.isShowBadge = YES;
} else {
weakSelf.rightBt.isShowBadge = NO;
}
// 发送信号量
dispatch_semaphore_signal(semaphore);
} andError:^(NSError *error) {
dispatch_semaphore_signal(semaphore);
}];
});

dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// 发起网络请求
[BadgeCountModel HomeDetailBadgeCountBlock:^(NSArray *data) {
if (!weakSelf.badgeDict) {
weakSelf.badgeDict = [NSMutableDictionary dictionary];
}
[weakSelf.badgeDict removeAllObjects];
NSMutableArray *badgeArray = [NSMutableArray array];
for (NSDictionary *dict in data) {
BadgeCountModel *model = [[BadgeCountModel alloc] init];
model.code = [NSString stringWithFormat:@"%@",dict[@"key"]];
model.value = [NSString stringWithFormat:@"%@",dict[@"value"]];
[badgeArray addObject:model];
NSIndexPath *path = [self getIndexPathWithCode:model.code];
if (!path) {
continue;
}
[weakSelf.badgeDict setObject:model.value forKey:path];
}
[weakSelf.collectionView reloadData];
[[GLMenuManager shareInstance] setRedPointArray:badgeArray];
dispatch_semaphore_signal(semaphore);
} andError:^(NSError *error) {
dispatch_semaphore_signal(semaphore);
}];
});

2. GCD单例

1
2
3
4
5
6
7
8
+ (instancetype)shared {
static Share *shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [[Share alloc]init];
});
return shared;
}
坚持原创技术分享,您的支持将鼓励我继续创作!